package com.youlian.utils.bitmap;

import java.lang.ref.SoftReference;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

import com.youlian.utils.MyLog;
import com.youlian.utils.Utils;
import com.youlian.utils.connection.BaseExecutor;
import com.youlian.utils.connection.BaseTask;
import com.youlian.utils.connection.OnTaskHandlerListener;
import com.youlian.utils.http.HTTPClientHelper;

/**
 * @author simon
 * @proName vipshop_1.0
 * @version 1.0
 * @Data 2012-9-20 下午05:25:54
 *
 *       <b>Comment...</b>
 */
public class BitmapManager implements OnTaskHandlerListener{

	public final Map<String, SoftReference<Bitmap>> cache;
//	private final ExecutorService pool;
	public int VIEW_WIDTH=0;
	public Map<ImageView, String> imageViews;
	private Bitmap placeholder;
	private final Object mLock = new Object();
	private boolean isDown = true;

	protected BaseExecutor mConnectionTask;
	private MyHandler myHandler;

	public BitmapManager(){
		imageViews = Collections.synchronizedMap(new LinkedHashMap<ImageView, String>());
		cache = Collections.synchronizedMap(new LinkedHashMap<String, SoftReference<Bitmap>>());
		mConnectionTask = new BaseExecutor(this);
		myHandler = new MyHandler();
	}



	/**
	 *
	 * @param url
	 * @param imageView
	 */
	public void loadBitmap(String url, final ImageView imageView) {
		imageViews.put(imageView, url);
		if(isDown){
			Bitmap bitmap = getBitmapFromCache(url);
			if (!Utils.isNull(bitmap)) {
				MyLog.info(getClass(), "读取缓存..............");
				imageView.setImageBitmap(bitmap);
			} else {
				imageView.setImageBitmap(placeholder);
				async(1,url,imageView);
			}
		}
	}

	/**
	 *
	 * @param url
	 * @param view
	 * @return
	 */
	private Bitmap downloadBitmap(String url, ImageView view) {
		Bitmap bitmap = null;
		Bitmap cornerBmp = null;
		byte[] bytes;
		try {
			MyLog.info(getClass(), "开始下载：" + url);
			bytes = Utils.openStream(HTTPClientHelper.getInputStream(url));
			if (bytes.length > 500) {
				bitmap = BitmapUtils.getCorrectBmp(bytes, 0, Config.RGB_565);
			}
			if(VIEW_WIDTH==0){
				return bitmap;
			}
			if (bitmap != null) {
				float scale = (float) (VIEW_WIDTH) / bitmap.getWidth();
				cornerBmp = BitmapUtils.getScaleBitmap(bitmap, scale);

				if(bitmap!=cornerBmp && bitmap != null && !bitmap.isRecycled()) {
					bitmap.recycle();
					bitmap = null;
				}
			}
			return cornerBmp;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (OutOfMemoryError e) {
		}

		return null;
	}

	protected void async(Runnable task){
		if(Utils.notNull(mConnectionTask))
			mConnectionTask.connectInPool(task)	;
	}

	/**
	 * start a parallel thread
	 * @param action
	 * @param params
	 */
	protected void async(int action,Object... params){
		BaseTask task = new BaseTask(action, params);
		async(task);
	}

	/**
	 * parallel asyn task
	 * @param task
	 */
	private void async(BaseTask task){
		if(Utils.notNull(mConnectionTask))
			mConnectionTask.connectInPool(task)	;
	}

	/**
	 * start a list thread
	 * @param action
	 * @param params
	 */
	protected void sync(int action,Object... params){
		BaseTask task = new BaseTask(action, params);
		sync(task);
	}

	/**
	 * linked list task
	 * @param task
	 */
	private void sync(BaseTask task){
		if(!Utils.notNull(mConnectionTask)){
			MyLog.error(getClass(), "---mConnectionTask null------");
			mConnectionTask = new BaseExecutor(this);
		}
		mConnectionTask.connectInQueue(task);
	}


	@Override
	public Object onConnection(int action, Object... params) throws Exception {
		// TODO Auto-generated method stub
		Object res =null;
		if(isDown){
			try {
				String downUrl = params[0].toString();
				MyLog.error(getClass(), "downUrl:"+downUrl);
				ImageView imageView = (ImageView)params[1];
				Bitmap bmp = downloadBitmap(downUrl,imageView);
				if(bmp!=null){
					res = new Object[]{bmp,imageView,downUrl};
					cache.put(downUrl, new SoftReference<Bitmap>(bmp));
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		return res;
	}

	@Override
	public void onProcessData(int action, Object data, Object... params) {
		// TODO Auto-generated method stub
		try {
			if(data!=null){
				Object[] obj = (Object[])data;
				Bitmap bmp = (Bitmap) obj[0];
				ImageView imageView = (ImageView)obj[1];
				String url = obj[2].toString();
				String tag = imageViews.get(imageView);
				if (tag != null && tag.equals(url)) {
					if (bmp != null) {
						MyLog.error(getClass(), "下载成功：" + url);
						imageView.setImageBitmap(bmp);
					} else {
						imageView.setImageBitmap(placeholder);
					}
				}

			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@Override
	public void onException(int action, Exception exception, Object... params) {
		// TODO Auto-generated method stub
		MyLog.debug(getClass(), "onException...");

	}

	public void stopDown(){
		MyLog.error(getClass(), "========================停止下载===========================");
		isDown = false;
		if(Utils.notNull(mConnectionTask)){
			mConnectionTask.disconnect();
		}
	}

	public void startDonw(){
		isDown = true;

	}

	public void imageViewsclear() {
		if (imageViews != null) {
			imageViews.clear();
		}
	}
	private final int REVYCLE=123;

	private class MyHandler extends Handler{
		@Override
		public void dispatchMessage(Message msg) {
			// TODO Auto-generated method stub
			super.dispatchMessage(msg);
			BitmapUtils.recycleBitmaps(cache);
		}
	}
	/**
	 *
	 */
	private Runnable myRunnable= new Runnable() {
		@Override
		public void run() {
			Message msg = myHandler.obtainMessage();
			msg.sendToTarget();
		}
	};
	/**
	 *
	 */
	public void destory() {
		stopDown();
		imageViewsclear();
		if (cache != null) {
			myHandler.postDelayed(myRunnable, 800);
		}
	}

	public void setPlaceholder(Bitmap bmp) {
		placeholder = bmp;
	}

	public Bitmap getBitmapFromCache(String url) {
		synchronized (url) {
			if (cache.containsKey(url)) {
				return cache.get(url).get();
			}
		}
		return null;
	}

	public void queueJob(final String url, final ImageView imageView) {
		/* Create handler in UI thread. */
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				String tag = imageViews.get(imageView);
				if (tag != null && tag.equals(url)) {
					if (msg.obj != null) {
						MyLog.error(getClass(), "下载成功：" + url);
						imageView.setImageBitmap((Bitmap) msg.obj);
					} else {
						imageView.setImageBitmap(placeholder);
					}
				}
			}
		};
	}

}